#include "sr.h"

static int state;
static char value;

#define READY  1
#define RUNNING  2

void
initControlBrake(void) {
    state = READY;
    value = 1;
}

void
controlBrakeFire(double posDesired, char brakeCond, char isKnown, char *brake, 
        int hasEventFlags, int *craneKnownFlags, int *cranePresentFlags) {

    char res = 0;
    if(state == RUNNING) {
        if(GET_BIT(*craneKnownFlags, ISKNOWNBIT) &&
               GET_BIT(*craneKnownFlags, BRAKECONDITIONBIT)) {

            if(GET_BIT(*cranePresentFlags, ISKNOWNBIT)) {
                if(isKnown == 1) {
                    res = 1;
                }
            }
            if(GET_BIT(*cranePresentFlags, BRAKECONDITIONBIT)) {
                if(brakeCond == 1) {
                    res = 1;
                }
            }

            if(GET_BIT(hasEventFlags, POSDESIREDBIT))  {
                value = 0;
            }

            if(res == 1) {
                value = 1;
            }

            if(GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                value = 1;
            }

            *brake = value;
            SET_BIT_TRUE(*craneKnownFlags, BRAKEBIT);
            SET_BIT_TRUE(*cranePresentFlags, BRAKEBIT);
        }
    }
}

void controlBrakePostfire(int hasEventFlags, int craneKnownFlags, 
        int cranePresentFlags) {

    switch(state) {
        case READY : {
            if(GET_BIT(craneKnownFlags, TRIGGERBIT)) {
                if(GET_BIT(cranePresentFlags, TRIGGERBIT)) {
                    state = RUNNING;
                }
            }
        } break;

        case RUNNING : {
            if(GET_BIT(hasEventFlags, SHUTDOWNBIT)) {
                initControlBrake();
                break;
            }

            if(GET_BIT(craneKnownFlags, EMSTOPMERGERBIT)) {
                if(GET_BIT(cranePresentFlags, EMSTOPMERGERBIT)) {
                    initControlBrake();
                }
            }
        } break;
    }
}
